<?php

// SilverStripe Diary Module 0.0.2
// 17.07.2010
// Author:  nivanka@silverstripers.com
                                      
class DiaryHolder extends Page{
    
	static $icon = "diary/images/Calendar";

	static $many_many = array(
      'Events' => 'DiaryEvent'
	);
	
	static $has_one = array(
		"Sidebar" => "WidgetArea",
    );
	
	static $db = array(
		"RSSItems" => "Int"
	);
	
	static $defaults = array(
		"RSSItems" => 10
	);
	
	/*
	 * Get the Fields needed by the CMS back end
	*/
	function getCMSFields(){

		$fields = parent::getCMSFields();
		
		$fields->addFieldToTab("Root.Content.Main", new NumericField("RSSItems", "Number of items to display in the RSS reed"));
		
		$tablefield = new ManyManyComplexTableField(
			$this,
			'Events',
			'DiaryEvent',
			array(
				'Start' => 'Start',
				'End' => 'End',
				'Title' => 'Title',
			),
			'getCMSFields_forPopup'
		);
		$tablefield->setAddTitle( 'Diary Events' );

		$fields->addFieldToTab( 'Root.Content.Events', $tablefield );
		
		if(!$fields->dataFieldByName("Sidebar")) {
			$fields->addFieldToTab("Root.Content.Widgets", new WidgetAreaEditor("Sidebar"));
		} 
		return $fields;	
	}
	
	/*
	 * Create a first Calendar while running the installation
	*/
	function requireDefaultRecords() {
		
		parent::requireDefaultRecords();
		
		if(!DataObject::get_one('DiaryHolder')) {
		
			$calendarholder = new DiaryHolder();
			$calendarholder->Title = "Diary";
			$calendarholder->URLSegment = "my-diary";
			$calendarholder->Status = "Published";
			$calendarholder->Content = "SilverStripe diary module installed successfully, you can start writing your diary now.";
			$calendarholder->write();
			$calendarholder->publish("Stage", "Live");
		}
	}
	
}

class DiaryHolder_Controller extends Page_Controller{
	
	/*
	 * The initializing function, this calls all the CSS and the Javascripts which the module needs
	*/
	function init(){
	
		parent::init();	
		if(Director::fileExists(project() . "/css/diary.css")) {
	    	Requirements::css(project() . "/css/diary.css");
		}
		else{
        	Requirements::css("diary/css/diary.css");
     	}
		Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js");
		Requirements::javascript("diary/javascript/diary.js");
	}
	/*
	 * Get the link to the previous month
	*/
	function getPreviousMonth(){
		// get todays date.
		$today = getdate();
		//if the date is not today
		if(isset($_GET['month'])){
			$today = getdate((int)$_GET['month']);
		}
		$lastmonth = getdate( mktime(0,0,0,$today['mon'] - 1 ,1,$today['year']) );
		$output = new DataObjectSet();
		$output->push(
			new ArrayData(
				array(
					"Link" => $this->URLSegment . "/?month=" . $lastmonth[0],
					"Name" => _t("DiaryHolder." . strtoupper($lastmonth['month']), $lastmonth['month']),
					"Title" => _t("DiaryHolder.PRE","Previous")
				)
			)
		);
		return $output;
	}
	
	/*
	 * Get the link to the next month
	*/
	function getNextMonth(){
		// get todays date.
		$today = getdate();
		//if the date is not today
		if(isset($_GET['month'])){
			$today = getdate((int)$_GET['month']);
		}
		$lastmonth = getdate( mktime(0,0,0,$today['mon'] + 1 ,1,$today['year']) );
		$output = new DataObjectSet();
		$output->push(
			new ArrayData(
				array(
					"Link" => $this->URLSegment . "/?month=" . $lastmonth[0],
					"Name" => _t("DiaryHolder." . strtoupper($lastmonth['month']), $lastmonth['month']),
					"Title" => _t("DiaryHolder.NEXT","Next")
				)
			)
		);
		return $output;
	}
	
	
	/*
	 * Get the exact month's calendar
	*/
	function getCalendar(){
		// get todays date.
		$today = getdate();
		//if the date is not today
		if(isset($_GET['month'])){
			$today = getdate((int)$_GET['month']);
		}
		$firstday = getdate( mktime(0,0,0,$today['mon'],1,$today['year']) );
		$lastday = getdate( mktime(0,0,0,$today['mon'] + 1,0,$today['year']) );
		$output = new DataObjectSet();
		$days = new DataObjectSet();
		
		for($i = 0; $i < ($lastday['mday'] - $firstday['mday'] + 1); $i++){
			
			$oddeven = "odd";
			$oddeven = ($i % 2 == 0) ? "odd" : "even";
			
			$thisday = getdate(mktime(0,0,0,$today['mon'],$i + 1,$today['year']));
			
			$today_to_search = $thisday['year'] . "-" . $thisday['mon'] . "-" . $thisday['mday'];
			
			//get the event is type is not choosen
			$events = DataObject::get("DiaryEvent","DiaryHolderID = '" . $this->ID ."' AND (Start = '$today_to_search' OR End = '$today_to_search' OR '$today_to_search' BETWEEN Start AND End)", "StartTime", "JOIN DiaryHolder_Events ON `DiaryEvent`.ID = DiaryHolder_Events.DiaryEventID");
			//get the events if the type is choosen
			if(strcmp(Session::get("EventType"),"all") && strcmp(Session::get("EventType"),"") ){
				$events = DataObject::get("DiaryEvent","DiaryHolderID = '" . $this->ID ."' AND (Start = '$today_to_search' OR End = '$today_to_search' OR '$today_to_search' BETWEEN Start AND End) AND EventType = '" . Session::get("EventType") ."'", "StartTime", "JOIN DiaryHolder_Events ON `DiaryEvent`.ID = DiaryHolder_Events.DiaryEventID");
			}
			
			$days->push(
				new ArrayData(
					array(
						"Date" => ($i + 1),
						"Day" =>  _t('DiaryHolder.' . strtoupper(substr($thisday['weekday'],0,3)),substr($thisday['weekday'],0,3)),
						"Mon" => _t('DiaryHolder.' . strtoupper(substr($thisday['month'],0,3)),substr($thisday['month'],0,3)),
						"Year" => $today['year'],
						"oddeven" => $oddeven,
						"Events" => $events,
						"Epoch" => $thisday[0]
					)
				)
			);
		}
		$output->push(
			new ArrayData(
				array(
					"Month" => _t('DiaryHolder.' . strtoupper($today['month']), $today['month'] ),
					"Year" => $today['year'],
					"Days" => $days
				)
			)
		);
		
		return $output;
		
	}
	
	/*
	 * Delete an entry
	*/
	function delete(){
		$params = Director::urlParams();
		if(isset($params['ID']))
			DataObject::delete_by_id("DiaryEvent",(int)$params['ID']);
		Director::redirectback();
		
	}
	
	/*
	 * Get entry by an id
	*/
	function getEvent(){
		$params = Director::urlParams();
		if(isset($params['ID']))
			return DataObject::get_by_id("DiaryEvent",(int)$params['ID']);
		elseif(isset($_REQUEST['ID']))
			return DataObject::get_by_id("DiaryEvent",(int)$_REQUEST['ID']);
		else
			return false;
	}
	
	/*
	 * Edit an ad
	*/
	function edit(){
		return array(
			"Title" => "Edit an event",
			"Form" => $this->EditEventForm()
		);
	}
	
	/*
	 * Edit Event Form this function returns a form which is used to edit a specific event
	*/
	function EditEventForm(){

		$event = $this->getEvent();
		if(empty($event)){
			return _t('DiaryHolder.ENTRYNOTFOUND',"Entry not found.");
		}
        $startDate = new DateField('Start', 'Starting date');
		$startDate->setConfig('showcalendar' , true);
		$startDate->setLocale("en_US");
		$startDate->setConfig('dateformat', 'dd/MM/YYYY');
		$startDate->setValue($event->Start);
		 
		$endDate = new DateField('End', 'Ending date');
		$endDate->setConfig('showcalendar' , true);
		$endDate->setLocale("en_US");
		$endDate->setConfig('dateformat', 'dd/MM/YYYY');
        $endDate->setValue($event->End);

		$startTime = new TimeField('StartTime', 'Start Time');
		$startTime->setConfig('showdropdown', true);
		$startTime->setValue($event->StartTime);
		
		$endTime = new TimeField('EndTime', 'End Time');
        $endTime->setConfig('showdropdown', true);
        $endTime->setValue($event->EndTime);

		return new Form($this, "EditEventForm",
			new FieldSet(
				new TextField("Title", "Title", ($event->Title)
												? $event->Title
												: "" ),
				new TextField("EventType", "Event Type", $value = $event->EventType),
				$startDate,
				$endDate,
				$startTime,
				$endTime,
				new TextField("Location", "Location", $value = $event->Location),
				new TextareaField("EventContent", "Content", 4, 5, $value = $event->Content),
				new HiddenField("ID", "ID", ($event->ID)
													? $event->ID
													: "" )
			),
			new FieldSet(
				new FormAction("editAnEvent", "Edit")
			),
			new RequiredFields("Title", "Start", "End"));


	}
	
	/*
	 * Edit event form processing
	*/
	function editAnEvent($data, $form){
		$event = DataObject::get_by_id("DiaryEvent",(int)$data['ID']);
		
		if($event){
			echo $data['Start'];
			
			$start = explode("/",$data['Start']);
			$start = implode("-",array($start[2], $start[1], $start[0]));
			
			$end = explode("/",$data['End']);
			$end = implode("-",array($end[2], $end[1], $end[0]));
			
			$event->Title = $data['Title'];
			$event->Start = $start;
			$event->End = $end;
			$event->StartTime = $data['StartTime'];
			$event->EndTime = $data['EndTime'];
			$event->Location = $data['Location'];
			$event->EventType = $data['EventType'];
			$event->Content = $data['EventContent'];
			
			$event->write();
			
			Director::redirectback();
			
		}
		else{
			return "Sorry! This event cannot be found in the database any more.";
		}
	}
	
	/*
	 * View a calendar event
	*/
	
	function view(){
		return array(
			"Title" => "View Event"
		);
	}
	
	/*
	 * view event type
	*/
	function type(){
		$params = Director::urlParams();
		if(isset($params['ID'])){
			Session::set("EventType",Convert::raw2sql($params['ID']));
			$cal = DataObject::get_one('DiaryHolder');
			Director::redirect($cal->Link());
		}
	}
	
	/*
	 * Set the month for the calendar widget
	 */
	function setMonth(){
		Session::set("CalMonth",(int)$_GET['month']);
		Director::redirect($_GET['back']."/");
	}
	
	/*
	 * Events RSS Feed Link
	 */
	function RSSLink(){
		return $this->Link() . "rss";
	}
	/*
	 * Events RSS Feed
	 */
	function rss(){
		$events = DataObject::get("DiaryEvent","","StartTime","", $this->RSSItems);
		$rss = new RSSFeed($events, $this->Link(), "Most recent events");
		$rss->outputToBrowser();
	}
	
	/**
	 * Navigate through months return the form
	 */                       
	function MonthNavigateForm(){
		
		$year = date("Y", time()) - 11;
		$yearArray = array();
		for($i = 0; $i < 22; $i++){
			$yearArray[$year + $i] = $year + $i;
		}
		$yearSel = date('Y');
		$monthSel = date('m');
		
		if(isset($_GET['month'])){
			$yearSel = date('Y', $_GET['month']);
			$monthSel = date('m', $_GET['month']);
		}
		
		$date = new CompositeField(
			new DropdownField("Month", "Month", array(
				"01" => "01", 
				"02" => "02", 
				"03" => "03", 
				"04" => "04", 
				"05" => "05", 
				"06" => "06", 
				"07" => "07", 
				"08" => "08", 
				"09" => "09", 
				"10" => "10", 
				"11" => "11", 
				"12" => "12"
			), $monthSel),
			new DropdownField("Year", "Year", $yearArray, $yearSel)
		);

		return new Form( 
			$this,
			"MonthNavigateForm",
			new FieldSet(
				$date
			),
			new FieldSet(
				new  FormAction("goNavigate", "Go")
			),
			new RequiredFields("Date")
		);
	} 
	
	/**
	 * redirect to the navigation page
	 */
	function goNavigate($data, $form){
		$date = $data['Month'] . "/01/" . $data['Year'];
		return Director::redirect($this->Link() . "?month=" . strtotime($date));
	}  
	
}

